<template>
  <div class="prescription-drug">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <div class="status-left">9:41</div>
      <div class="status-right">
        <div class="signal"></div>
        <div class="wifi"></div>
        <div class="battery"></div>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="header">
      <div class="nav-back" @click="goBack">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
      </div>
      <h1 class="page-title">处方药</h1>
      <div class="nav-action">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.35-4.35"/>
        </svg>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-section">
      <div class="search-bar">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.35-4.35"/>
        </svg>
        <input 
          type="text" 
          placeholder="搜索处方药..." 
          v-model="searchQuery"
          @input="handleSearch"
        />
        <div class="search-filter" @click="showFilter = !showFilter">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#999" stroke-width="2">
            <polygon points="22,3 2,3 10,12.46 10,19 14,21 14,12.46"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 筛选选项 -->
    <div class="filter-section" v-if="showFilter">
      <div class="filter-tabs">
        <div 
          class="filter-tab" 
          :class="{ active: activeFilter === 'all' }"
          @click="setFilter('all')"
        >
          全部
        </div>
        <div 
          class="filter-tab" 
          :class="{ active: activeFilter === 'pending' }"
          @click="setFilter('pending')"
        >
          待取药
        </div>
        <div 
          class="filter-tab" 
          :class="{ active: activeFilter === 'completed' }"
          @click="setFilter('completed')"
        >
          已完成
        </div>
      </div>
    </div>

    <!-- 处方列表 -->
    <div class="prescription-list" ref="listContainer" @scroll="handleScroll">
      <div 
        class="prescription-card" 
        v-for="prescription in displayedPrescriptions" 
        :key="prescription.id"
        @click="viewPrescription(prescription)"
      >
        <div class="prescription-header">
          <div class="prescription-info">
            <h3 class="prescription-title">{{ prescription.title }}</h3>
            <p class="prescription-doctor">医生：{{ prescription.doctor }}</p>
            <p class="prescription-date">{{ prescription.date }}</p>
          </div>
          <div class="prescription-status" :class="prescription.status">
            {{ getStatusText(prescription.status) }}
          </div>
        </div>
        
        <div class="prescription-details">
          <div class="medicine-count">
            <span class="count">{{ prescription.medicines.length }}</span>
            <span class="label">种药品</span>
          </div>
          <div class="prescription-actions">
            <button class="action-btn primary" @click.stop="pickupMedicine(prescription)">
              取药
            </button>
            <button class="action-btn secondary" @click.stop="viewDetails(prescription)">
              详情
            </button>
          </div>
        </div>

        <!-- 药品列表预览 -->
        <div class="medicine-preview" v-if="prescription.medicines.length > 0">
          <div class="medicine-item" v-for="medicine in prescription.medicines.slice(0, 3)" :key="medicine.id">
            <div class="medicine-icon">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
                <path d="M9 12l2 2 4-4"/>
                <path d="M21 12c-1 0-2-1-2-2s1-2 2-2 2 1 2 2-1 2-2 2z"/>
                <path d="M3 12c1 0 2-1 2-2s-1-2-2-2-2 1-2 2 1 2 2 2z"/>
              </svg>
            </div>
            <span class="medicine-name">{{ medicine.name }}</span>
            <span class="medicine-dosage">{{ medicine.dosage }}</span>
          </div>
          <div class="more-medicines" v-if="prescription.medicines.length > 3">
            +{{ prescription.medicines.length - 3 }}种
          </div>
        </div>
      </div>

      <!-- 加载更多指示器 -->
      <div class="load-more" v-if="isLoading">
        <div class="loading-spinner">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
            <circle cx="12" cy="12" r="10" stroke-dasharray="31.416" stroke-dashoffset="31.416">
              <animate attributeName="stroke-dasharray" dur="2s" values="0 31.416;15.708 15.708;0 31.416" repeatCount="indefinite"/>
              <animate attributeName="stroke-dashoffset" dur="2s" values="0;-15.708;-31.416" repeatCount="indefinite"/>
            </circle>
          </svg>
        </div>
        <span class="loading-text">加载中...</span>
      </div>

      <!-- 没有更多数据提示 -->
      <div class="no-more" v-if="!hasMore && displayedPrescriptions.length > 0">
        <span class="no-more-text">没有更多数据了</span>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="displayedPrescriptions.length === 0 && !isLoading">
      <div class="empty-icon">
        <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="#ccc" stroke-width="1">
          <path d="M9 12l2 2 4-4"/>
          <path d="M21 12c-1 0-2-1-2-2s1-2 2-2 2 1 2 2-1 2-2 2z"/>
          <path d="M3 12c1 0 2-1 2-2s-1-2-2-2-2 1-2 2 1 2 2 2z"/>
        </svg>
      </div>
      <h3 class="empty-title">暂无处方药</h3>
      <p class="empty-desc">您还没有处方药记录</p>
    </div>

    <!-- 底部导航 -->
    <div class="bottom-nav">
      <div class="nav-item" @click="goToHome">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
          <polyline points="9,22 9,12 15,12 15,22"/>
        </svg>
        <span>首页</span>
      </div>
      <div class="nav-item active">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M9 12l2 2 4-4"/>
          <path d="M21 12c-1 0-2-1-2-2s1-2 2-2 2 1 2 2-1 2-2 2z"/>
          <path d="M3 12c1 0 2-1 2-2s-1-2-2-2-2 1-2 2 1 2 2 2z"/>
        </svg>
        <span>处方药</span>
      </div>
      <div class="nav-item" @click="goToProfile">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
          <circle cx="12" cy="7" r="4"/>
        </svg>
        <span>我的</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const showFilter = ref(false)
const activeFilter = ref('all')
const isLoading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(10)
const listContainer = ref<HTMLElement>()

// 生成更多模拟处方数据
const generateMockPrescriptions = (startId: number, count: number) => {
  const prescriptions = []
  const titles = [
    '感冒发烧处方', '高血压处方', '糖尿病处方', '心脏病处方', '胃病处方',
    '头痛处方', '失眠处方', '关节炎处方', '哮喘处方', '皮肤病处方',
    '眼科处方', '耳鼻喉处方', '妇科处方', '儿科处方', '骨科处方',
    '神经科处方', '精神科处方', '肿瘤科处方', '血液科处方', '内分泌科处方'
  ]
  const doctors = ['张医生', '李医生', '王医生', '刘医生', '陈医生', '赵医生', '孙医生', '周医生', '吴医生', '郑医生']
  const medicines = [
    { name: '布洛芬缓释胶囊', dosage: '0.3g × 10粒' },
    { name: '感冒灵颗粒', dosage: '10g × 6袋' },
    { name: '维生素C片', dosage: '0.1g × 20片' },
    { name: '板蓝根颗粒', dosage: '10g × 8袋' },
    { name: '硝苯地平缓释片', dosage: '30mg × 7片' },
    { name: '厄贝沙坦片', dosage: '150mg × 7片' },
    { name: '二甲双胍片', dosage: '0.5g × 30片' },
    { name: '格列美脲片', dosage: '2mg × 30片' },
    { name: '阿卡波糖片', dosage: '50mg × 30片' },
    { name: '阿司匹林肠溶片', dosage: '100mg × 30片' },
    { name: '辛伐他汀片', dosage: '20mg × 7片' },
    { name: '奥美拉唑胶囊', dosage: '20mg × 14粒' },
    { name: '雷贝拉唑钠肠溶片', dosage: '10mg × 14片' },
    { name: '多潘立酮片', dosage: '10mg × 30片' },
    { name: '蒙脱石散', dosage: '3g × 10袋' }
  ]

  for (let i = 0; i < count; i++) {
    const id = startId + i
    const title = titles[Math.floor(Math.random() * titles.length)]
    const doctor = doctors[Math.floor(Math.random() * doctors.length)]
    const status = Math.random() > 0.5 ? 'pending' : 'completed'
    const medicineCount = Math.floor(Math.random() * 5) + 2 // 2-6种药品
    const prescriptionMedicines = []
    
    // 随机选择药品
    const shuffledMedicines = [...medicines].sort(() => Math.random() - 0.5)
    for (let j = 0; j < medicineCount; j++) {
      prescriptionMedicines.push({
        id: j + 1,
        name: shuffledMedicines[j].name,
        dosage: shuffledMedicines[j].dosage
      })
    }

    // 生成随机日期（最近3个月内）
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 90))
    const dateString = date.toISOString().split('T')[0]

    prescriptions.push({
      id,
      title,
      doctor,
      date: dateString,
      status,
      medicines: prescriptionMedicines
    })
  }

  return prescriptions
}

// 所有处方数据
const allPrescriptions = ref(generateMockPrescriptions(1, 50))

// 当前显示的处方数据（用于懒加载）
const displayedPrescriptions = ref<any[]>([])

// 计算属性
const filteredPrescriptions = computed(() => {
  let filtered = allPrescriptions.value

  // 按状态筛选
  if (activeFilter.value !== 'all') {
    filtered = filtered.filter(p => p.status === activeFilter.value)
  }

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(p => 
      p.title.toLowerCase().includes(query) ||
      p.doctor.toLowerCase().includes(query) ||
      p.medicines.some(m => m.name.toLowerCase().includes(query))
    )
  }

  return filtered
})

// 加载更多数据
const loadMoreData = async () => {
  if (isLoading.value || !hasMore.value) return

  isLoading.value = true
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 1000))

  const filtered = filteredPrescriptions.value
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  const newData = filtered.slice(startIndex, endIndex)

  if (newData.length > 0) {
    displayedPrescriptions.value.push(...newData)
    currentPage.value++
  }

  // 检查是否还有更多数据
  hasMore.value = endIndex < filtered.length
  isLoading.value = false
}

// 重置数据
const resetData = () => {
  displayedPrescriptions.value = []
  currentPage.value = 1
  hasMore.value = true
  loadMoreData()
}

// 滚动处理
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 当滚动到距离底部100px时加载更多
  if (scrollHeight - scrollTop - clientHeight < 100 && !isLoading.value && hasMore.value) {
    loadMoreData()
  }
}

// 方法
const goBack = () => {
  router.back()
}

const handleSearch = () => {
  resetData()
}

const setFilter = (filter: string) => {
  activeFilter.value = filter
  resetData()
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待取药'
    case 'completed': return '已完成'
    default: return '未知'
  }
}

const viewPrescription = (prescription: any) => {
  console.log('查看处方:', prescription)
  // 这里可以跳转到处方详情页
}

const pickupMedicine = (prescription: any) => {
  console.log('取药:', prescription)
  // 这里可以处理取药逻辑
  prescription.status = 'completed'
}

const viewDetails = (prescription: any) => {
  console.log('查看详情:', prescription)
  // 这里可以跳转到详情页
}

const goToHome = () => {
  router.push('/medical-home')
}

const goToProfile = () => {
  router.push('/medical-home')
}

// 监听筛选和搜索变化
const watchFilteredData = () => {
  resetData()
}

// 组件挂载时加载初始数据
onMounted(() => {
  nextTick(() => {
    loadMoreData()
  })
})
</script>

<style scoped lang="scss">
.prescription-drug {
  min-height: 100vh;
  background: #f5f5f5;
  position: relative;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #000;
  color: white;
  font-size: 14px;
  font-weight: 600;

  .status-right {
    display: flex;
    gap: 5px;
    align-items: center;
  }

  .signal, .wifi, .battery {
    width: 20px;
    height: 12px;
    background: #fff;
    border-radius: 2px;
  }

  .signal {
    background: linear-gradient(90deg, #fff 0%, #fff 80%, transparent 80%);
  }

  .wifi {
    background: radial-gradient(circle at 50% 50%, transparent 0, transparent 3px, #fff 3px, #fff 6px, transparent 6px);
  }

  .battery {
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      right: -3px;
      top: 50%;
      transform: translateY(-50%);
      width: 2px;
      height: 6px;
      background: #fff;
      border-radius: 0 1px 1px 0;
    }
  }
}

.header {
  background: linear-gradient(135deg, #1877F2 0%, #005AFF 100%);
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: white;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>');
    opacity: 0.3;
  }
}

.nav-back, .nav-action {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s ease;
  position: relative;
  z-index: 1;

  &:hover {
    background: rgba(255, 255, 255, 0.3);
  }
}

.page-title {
  font-size: 20px;
  font-weight: 700;
  margin: 0;
  position: relative;
  z-index: 1;
}

.search-section {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.search-bar {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 12px 16px;
  gap: 12px;

  input {
    flex: 1;
    border: none;
    background: transparent;
    font-size: 16px;
    outline: none;
    color: #333;

    &::placeholder {
      color: #999;
    }
  }

  .search-filter {
    cursor: pointer;
    padding: 4px;
    border-radius: 6px;
    transition: background 0.3s ease;

    &:hover {
      background: #e9ecef;
    }
  }
}

.filter-section {
  background: white;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.filter-tabs {
  display: flex;
  gap: 12px;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 20px;
  background: #f8f9fa;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;

  &.active {
    background: #1877F2;
    color: white;
  }

  &:hover {
    background: #e9ecef;
    
    &.active {
      background: #1877F2;
    }
  }
}

.prescription-list {
  padding: 20px;
  padding-bottom: 100px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  scroll-behavior: smooth;
}

.prescription-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
}

.prescription-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.prescription-info {
  flex: 1;

  .prescription-title {
    font-size: 18px;
    font-weight: 700;
    color: #333;
    margin: 0 0 8px 0;
  }

  .prescription-doctor {
    font-size: 14px;
    color: #666;
    margin: 0 0 4px 0;
  }

  .prescription-date {
    font-size: 12px;
    color: #999;
    margin: 0;
  }
}

.prescription-status {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;

  &.pending {
    background: #fff3cd;
    color: #856404;
  }

  &.completed {
    background: #d4edda;
    color: #155724;
  }
}

.prescription-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.medicine-count {
  display: flex;
  align-items: center;
  gap: 8px;

  .count {
    font-size: 20px;
    font-weight: 700;
    color: #1877F2;
  }

  .label {
    font-size: 14px;
    color: #666;
  }
}

.prescription-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 8px 16px;
  border-radius: 8px;
  border: none;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;

  &.primary {
    background: #1877F2;
    color: white;

    &:hover {
      background: #005AFF;
    }
  }

  &.secondary {
    background: #f8f9fa;
    color: #666;
    border: 1px solid #e9ecef;

    &:hover {
      background: #e9ecef;
    }
  }
}

.medicine-preview {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.medicine-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.medicine-icon {
  width: 24px;
  height: 24px;
  border-radius: 6px;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.medicine-name {
  flex: 1;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.medicine-dosage {
  font-size: 12px;
  color: #999;
}

.more-medicines {
  font-size: 12px;
  color: #1877F2;
  text-align: center;
  margin-top: 8px;
  font-weight: 500;
}

// 加载更多样式
.load-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
}

.loading-spinner {
  margin-bottom: 8px;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.no-more {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.no-more-text {
  font-size: 14px;
  color: #999;
  font-style: italic;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  margin-bottom: 20px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: #666;
  margin: 0 0 8px 0;
}

.empty-desc {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 0;
  border-top: 1px solid #e0e0e0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #999;

  &.active {
    color: #1877F2;
    background: rgba(24, 119, 242, 0.1);
  }

  &:hover {
    background: rgba(24, 119, 242, 0.05);
    color: #1877F2;
  }

  span {
    font-size: 12px;
    font-weight: 500;
  }

  svg {
    transition: transform 0.3s ease;
  }

  &:hover svg {
    transform: scale(1.1);
  }
}

@media (max-width: 768px) {
  .prescription-list {
    padding: 15px;
  }

  .prescription-card {
    padding: 16px;
  }

  .prescription-actions {
    flex-direction: column;
    gap: 8px;
  }

  .action-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .header {
    padding: 15px;
  }

  .page-title {
    font-size: 18px;
  }

  .search-section {
    padding: 12px 15px;
  }

  .filter-section {
    padding: 12px 15px;
  }

  .filter-tabs {
    gap: 8px;
  }

  .filter-tab {
    padding: 6px 12px;
    font-size: 12px;
  }
}
</style> 